import React from 'react';
import TextField from '@material-ui/core/TextField';
import styles from './index.module.scss'
import Button from '@material-ui/core/Button';
import Switch from '@material-ui/core/Switch';
import DeleteIcon from '@material-ui/icons/Delete';

if (!global.backendPort) {
  global.backendPort = "4444"
}

export default function HomePage() {
  let ws = new WebSocket("ws://localhost:" + global.backendPort + "/web/app/events");
  ws.onmessage = (message) => {
    let obj = JSON.parse(message.data);
    if (obj.event == "updateBasRes") {
      console.log(obj.data)
    }
  }

  const [bas, setBas] = React.useState([{ name: "点击7", key: "7", interval: "500-1000" },
  { name: "点击8", key: "8", interval: "500-1000" },
  { name: "点击9", key: "9", interval: "500-1000" },
  { name: "点击鼠标左键", key: "left", interval: "500-1000" },
  { name: "点击鼠标右键", key: "right", interval: "500-1000" }])

  const handleInputChange = (index, key) => e => {
    bas[index][key] = e.target.value
    setBas(bas.slice())
  }

  React.useEffect(_ => {
    console.log("bas", bas)
  })

  const updateBas = _ => {
    ws.send(JSON.stringify({
      "event": "updateBas",
      "bas": bas
    }))
  }
  return (
    <div style={{ paddingTop: 10, paddingBottom: 10 }}>
      <div style={{ display: 'flex', width: '100%' }}>
        <div className={styles.title}>名称</div>
        <div className={styles.title}>按键</div>
        <div className={styles.title}>间隔</div>
        <div className={styles.title}>操作</div>
      </div>
      {bas.map((item, index) => {
        return (<div key={index} style={{ display: 'flex' }}>
          <div className={styles.input}>
            <TextField value={item.name} onChange={handleInputChange(index, "name")}></TextField>
          </div>
          <div className={styles.input}>
            <TextField value={item.key} onChange={handleInputChange(index, "key")}></TextField>
          </div>
          <div className={styles.input}>
            <TextField value={item.interval} onChange={handleInputChange(index, "interval")}></TextField>
          </div>
          <div className={styles.input}>
            <Switch
              checked={item.started}
              color="primary"
              onChange={e => {
                bas[index].started = e.target.checked
                setBas(bas.slice())
                updateBas()
              }}
            />

            <Button>
              <DeleteIcon color="secondary" onClick={_ => {
                bas.splice(index, 1)
                setBas(bas.slice())
                updateBas()
              }} />
            </Button>
          </div>
        </div>)
      })}

      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: 10 }}>
        <Button variant="contained" color="primary" onClick={_ => {
          bas.push({ name: "", key: "", interval: "" })
          setBas(bas.slice())
        }}>
          添加
        </Button>
      </div>
    </div>
  );
}
